package com.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 *  CAS自定义 自旋锁
 *
 * */
public class SpinLockDemo {

    //对象引用原子类
    AtomicReference atomicReference = new AtomicReference();
    //加锁
    public void lock(){
        Thread thread = Thread.currentThread();

        //等待死循环
        while(!atomicReference.compareAndSet(null,thread)){

        }
        System.out.println(Thread.currentThread().getName()+" ==> 拿到锁");
    }
    //解锁时 如果没拿到锁会CAS-自旋
    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+" ==>解锁");
    }
}
class test{
    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo lock = new SpinLockDemo();

        new Thread(()->{
            lock.lock();//加锁
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        },"T1").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            lock.lock();//加锁
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        },"T2").start();

    }
}
